﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


using System.Windows;
using System.Windows.Input;

using HA.Data;

using HA.ModFlow.Controls.Windows;

using HA.ModFlow.Controls.Windows.MapData;

using HA.ModFlow.Domain.DomainLayer;

using HAMath;

using HA.ModFlow.Infrastructure;

namespace HA.ModFlow.Application
{

    /// <summary>
    /// 封装projectview中相关的主程命令，是对于datacommands的补充，这里重要涉及到一些高级操作
    /// 包括离散点，tin等
    /// </summary>
   public static class Data2Commands
    {


       static Data2Commands()
       {

           addSactter2D = new RoutedCommand();
           removeSatter2D = new RoutedCommand();
           addScatter3D = new RoutedCommand();
           removeScatter3D = new RoutedCommand();

           //离散点  差值到modflow图层
           scatter2DToModflowLayer = new RoutedCommand();

           //离散点  差值到网格
           scatter2DToGrid3d = new RoutedCommand();

           //离散点  边框转换成三维网格
           scatterBoundToGrid3D = new RoutedCommand();



           grid3dProp = new RoutedCommand();



           ccfToDataSet = new RoutedCommand();

           flowBudget = new RoutedCommand();



           generateVector = new RoutedCommand();



           viewDSValue = new RoutedCommand();


           _copyDSGrid3dCollection = new RoutedCommand();

           _deleteDSGrid3d = new RoutedCommand();

           _deleteDSGrid3dCollection = new RoutedCommand();




 
       }

      
       static RoutedCommand _copyDSGrid3dCollection;
       /// <summary>
       ///拷贝DSGrid3dCollection数据
       /// </summary>
       public static RoutedCommand CopyDSGrid3dCollection
       {
           get { return Data2Commands._copyDSGrid3dCollection; }
       
       }

       static RoutedCommand _deleteDSGrid3dCollection;
       /// <summary>
       /// 删除DSGrid3dCollection数据
       /// </summary>
       public static RoutedCommand DeleteDSGrid3dCollection
       {
           get { return Data2Commands._deleteDSGrid3dCollection; }
          
       }


       static RoutedCommand _deleteDSGrid3d;
       /// <summary>
       /// 删除 DSGrid3d数据
       /// </summary>
       public static RoutedCommand DeleteDSGrid3d
       {
           get { return Data2Commands._deleteDSGrid3d; }
           
       }






       static RoutedCommand generateVector;

       public static RoutedCommand GenerateVector
       {
           get { return Data2Commands.generateVector; }
           
       }

       public static Window mainWindow;

       static RoutedCommand ccfToDataSet;

       public static RoutedCommand CcfToDataSet
       {
           get { return Data2Commands.ccfToDataSet; }
          
       }

       static RoutedCommand flowBudget;

       public static RoutedCommand FlowBudget
       {
           get { return Data2Commands.flowBudget; }
           set { Data2Commands.flowBudget = value; }
       }







       static RoutedCommand grid3dProp;

       public static RoutedCommand Grid3dProp
       {
           get { return Data2Commands.grid3dProp; }
          
       }






       static RoutedCommand addSactter2D;

       public static RoutedCommand AddSactter2D
       {
           get { return Data2Commands.addSactter2D; }

       }


       static RoutedCommand removeSatter2D;

       public static RoutedCommand RemoveSatter2D
       {
           get { return Data2Commands.removeSatter2D; }
       }

       static RoutedCommand addScatter3D;

       public static RoutedCommand AddScatter3D
       {
           get { return Data2Commands.addScatter3D; }
       }

       static RoutedCommand removeScatter3D;

       public static RoutedCommand RemoveScatter3D
       {
           get { return Data2Commands.removeScatter3D; }
       }



       static RoutedCommand scatter2DToModflowLayer;
       /// <summary>
       /// 离散点  差值到Modflow图层
       /// </summary>
       public static RoutedCommand Scatter2DToModflowLayer
       {
           get { return Data2Commands.scatter2DToModflowLayer; }
          
       }


       static RoutedCommand scatter2DToGrid3d;
       /// <summary>
       /// 离散点   差值到网格
       /// </summary>
       public static RoutedCommand Scatter2DToGrid3d
       {
           get { return Data2Commands.scatter2DToGrid3d; }
           //set { Data2Commands.scatter2DToGrid3d = value; }
       }




       static RoutedCommand scatterBoundToGrid3D;
       /// <summary>
       /// 离散点  边框转换成三维网格
       /// </summary>
       public static RoutedCommand ScatterBoundToGrid3D
       {
           get { return scatterBoundToGrid3D; }
       }





       static RoutedCommand viewDSValue;

       public static RoutedCommand ViewDSValue
       {
           get { return Data2Commands.viewDSValue; }
          
       }

       static RoutedCommand editScatterPoint = new RoutedCommand();

       public static RoutedCommand EditScatterPoint
       {
           get { return Data2Commands.editScatterPoint; }
           set { Data2Commands.editScatterPoint = value; }
       }

       static RoutedCommand viewVectorValue = new RoutedCommand();

       public static RoutedCommand ViewVectorValue
       {
           get { return Data2Commands.viewVectorValue; }       
       }

       public static void BindCommandsToWindow(Window window)
       {

           CommandBinding cbAddSactter2D = new CommandBinding();
           cbAddSactter2D.Command = addSactter2D;
           cbAddSactter2D.CanExecute += new CanExecuteRoutedEventHandler(cbAddSactter2D_CanExecute);
           cbAddSactter2D.Executed += new ExecutedRoutedEventHandler(cbAddSactter2D_Executed);
           window.CommandBindings.Add(cbAddSactter2D);

           CommandBinding cbRemoveSatter2D = new CommandBinding();
           cbRemoveSatter2D.Command = removeSatter2D;
           cbRemoveSatter2D.CanExecute += new CanExecuteRoutedEventHandler(cbRemoveSatter2D_CanExecute);
           cbRemoveSatter2D.Executed += new ExecutedRoutedEventHandler(cbRemoveSatter2D_Executed);
           window.CommandBindings.Add(cbRemoveSatter2D);

           CommandBinding cbAddScatter3D = new CommandBinding();
           cbAddScatter3D.Command = addScatter3D;
           cbAddScatter3D.CanExecute += new CanExecuteRoutedEventHandler(cbAddScatter3D_CanExecute);
           cbAddScatter3D.Executed += new ExecutedRoutedEventHandler(cbAddScatter3D_Executed);
           window.CommandBindings.Add(cbAddScatter3D);

           CommandBinding cbRemoveScatter3D = new CommandBinding();
           cbRemoveScatter3D.Command = removeScatter3D;
           cbRemoveScatter3D.CanExecute += new CanExecuteRoutedEventHandler(cbRemoveScatter3D_CanExecute);
           cbRemoveScatter3D.Executed += new ExecutedRoutedEventHandler(cbRemoveScatter3D_Executed);
           window.CommandBindings.Add(cbRemoveScatter3D);




           CommandBinding cbScatterToModflowLayer = new CommandBinding();
           cbScatterToModflowLayer.Command = scatter2DToModflowLayer;
           cbScatterToModflowLayer.CanExecute += new CanExecuteRoutedEventHandler(cbScatterToModflowLayer_CanExecute);
           cbScatterToModflowLayer.Executed += new ExecutedRoutedEventHandler(cbScatterToModflowLayer_Executed);
           window.CommandBindings.Add(cbScatterToModflowLayer);

           CommandBinding cbScatter2DToGrid3d = new CommandBinding();
           cbScatter2DToGrid3d.Command = scatter2DToGrid3d;
           cbScatter2DToGrid3d.CanExecute +=new  CanExecuteRoutedEventHandler(cbScatter2dToGrid3d_CanExecuted);
           cbScatter2DToGrid3d.Executed += new ExecutedRoutedEventHandler(cbScatter2dToGrid3d_Executed);

           window.CommandBindings.Add(cbScatter2DToGrid3d );



           CommandBinding cbScatterBoundToGrid3D = new CommandBinding();
           cbScatterBoundToGrid3D.Command = scatterBoundToGrid3D;
           cbScatterBoundToGrid3D.CanExecute += new CanExecuteRoutedEventHandler(cbScatterBoundToGrid3D_CanExecute);
           cbScatterBoundToGrid3D.Executed += new ExecutedRoutedEventHandler(cbScatterBoundToGrid3D_Execute);

           window.CommandBindings.Add(cbScatterBoundToGrid3D );




           CommandBinding cbGrid3dProp = new CommandBinding();
           cbGrid3dProp.Command = grid3dProp;
           cbGrid3dProp.CanExecute += new CanExecuteRoutedEventHandler(cbGrid3dProp_CanExecute);
           cbGrid3dProp.Executed += new ExecutedRoutedEventHandler(cbGrid3dProp_Executed);
           window.CommandBindings.Add(cbGrid3dProp);



           CommandBinding cbCCFToDS = new CommandBinding();
           cbCCFToDS.Command = ccfToDataSet;
           cbCCFToDS.CanExecute += new CanExecuteRoutedEventHandler(cbCCFToDS_CanExecute);
           cbCCFToDS.Executed += new ExecutedRoutedEventHandler(cbCCFToDS_Executed);
           window.CommandBindings.Add(cbCCFToDS);



           CommandBinding cbFlowBudget = new CommandBinding();
           cbFlowBudget.Command = flowBudget;
           cbFlowBudget.CanExecute += new CanExecuteRoutedEventHandler(cbFlowBudget_CanExecute);
           cbFlowBudget.Executed += new ExecutedRoutedEventHandler(cbFlowBudget_Executed);
           window.CommandBindings.Add(cbFlowBudget);


           CommandBinding cbViewDSValue = new CommandBinding();
           cbViewDSValue.Command = ViewDSValue;
           cbViewDSValue.CanExecute += new CanExecuteRoutedEventHandler(cbViewDSValue_CanExecute);
           cbViewDSValue.Executed += new ExecutedRoutedEventHandler(cbViewDSValue_Executed);
           window.CommandBindings.Add(cbViewDSValue);


           CommandBinding cbGenerateVector = new CommandBinding();
           cbGenerateVector.Command = generateVector;
           cbGenerateVector.CanExecute += new CanExecuteRoutedEventHandler(cbGenerateVector_CanExecute);
           cbGenerateVector.Executed += new ExecutedRoutedEventHandler(cbGenerateVector_Executed);
           window.CommandBindings.Add(cbGenerateVector);

           CommandBinding cbEditScatterPoint = new CommandBinding();
           cbEditScatterPoint.Command = editScatterPoint;
           cbEditScatterPoint.Executed += new ExecutedRoutedEventHandler(cbEditScatterPoint_Executed);
           cbEditScatterPoint.CanExecute += new CanExecuteRoutedEventHandler(cbEditScatterPoint_CanExecute);
           window.CommandBindings.Add(cbEditScatterPoint);

           CommandBinding cbViewVector = new CommandBinding();
           cbViewVector.Command = viewVectorValue;
           cbViewVector.CanExecute += new CanExecuteRoutedEventHandler(cbViewVector_CanExecute);
           cbViewVector.Executed += new ExecutedRoutedEventHandler(cbViewVector_Executed);
           window.CommandBindings.Add(cbViewVector);




           CommandBinding cbCopyDSGrid3dCollection = new CommandBinding();
           cbCopyDSGrid3dCollection.Command = _copyDSGrid3dCollection;
           cbCopyDSGrid3dCollection.CanExecute += new CanExecuteRoutedEventHandler(cbCopyDSGrid3dCollection_CanExecute);
           cbCopyDSGrid3dCollection.Executed += new ExecutedRoutedEventHandler(cbCopyDSGrid3dCollection_Execute );
           window.CommandBindings.Add(cbCopyDSGrid3dCollection );



           CommandBinding cbDeleteDSGrid3dCollection = new CommandBinding();
           cbDeleteDSGrid3dCollection.Command = _deleteDSGrid3dCollection ;
           cbDeleteDSGrid3dCollection.CanExecute += new CanExecuteRoutedEventHandler(cbDeleteDSGrid3dCollection_CanExecute);
           cbDeleteDSGrid3dCollection.Executed += new ExecutedRoutedEventHandler(cbDeleteDSGrid3dCollection_Execute);
           window.CommandBindings.Add(cbDeleteDSGrid3dCollection);




           CommandBinding cbDeleteDSGrid3d = new CommandBinding();
           cbDeleteDSGrid3d.Command = _deleteDSGrid3d ;
           cbDeleteDSGrid3d.CanExecute += new CanExecuteRoutedEventHandler(cbDeleteDSGrid3d_CanExecute);
           cbDeleteDSGrid3d.Executed += new ExecutedRoutedEventHandler(cbDeleteSGrid3d_Execute);
           window.CommandBindings.Add(cbDeleteDSGrid3d);

        
       }

    


       static void cbCopyDSGrid3dCollection_CanExecute(object sender,CanExecuteRoutedEventArgs e) 
       {
           //先简单的设置为true

           e.CanExecute = true;


       }
       /// <summary>
       /// 删除 DSGrid3dCollecion
       /// </summary>
       /// <param name="sender"></param>
       /// <param name="e"></param>
       static void cbCopyDSGrid3dCollection_Execute(object sender, ExecutedRoutedEventArgs e)
       {
           DSGrid3dCollecion dsGrid3dCollection = (DSGrid3dCollecion)e.Parameter;


           if (dsGrid3dCollection == null)
           {
               return;
           }
           if (dsGrid3dCollection.Key.ToString().Trim() == "ModflowResult" || dsGrid3dCollection.Key.ToString().Trim() == "MT3DMSResult")
           {
           }
           else
           {
               return;
           }
           //新拷贝出来的数据集的 Key 如何设置呢？使用时间比较好一些，但是各个机器的时间格式不统一，转换成字符串后导致复杂性加剧System.DateTime .Now .ToString ();不靠谱
           //暂时使用简单的计数器吧

           Grid3d grid3d = ProjectService.DefaultService.Project.Grid3dData.MainGrid;
           if (grid3d == null || grid3d.DatasetCollecion == null)
           {
               return;
           }



           int contout = 0;//计数器

           string oldKey = dsGrid3dCollection.Key.ToString().Trim();//ModflowResult  或者  MT3DMSResult

           for (int i = 0; i < grid3d.DatasetCollecion.Count; i++)
           {
               if (grid3d.DatasetCollecion[i].Key.ToString().Trim().Contains(oldKey))
               {
                   contout = contout + 1;
               }
           }

           string key = "";
           try
           {
               if (contout > 0)
               {

                   #region  已经存在ModflowResult/MT3DMSResult 或者拷贝的数据集

                   if (contout == 1)
                   {
                       //不存在拷贝的数据集

                       key = oldKey + "_Copy_" + contout.ToString();
                   }
                   if (contout > 1 && contout < 6)
                   {
                       //已经存在拷贝的数据集  拷贝的数据集个数可能为  1，2，3，4
                       //取得_Copy_后的数字最大者  往后叠加  不会超过5  最多拷贝5个方案
                       //计算取得  DSGrid3dCollection  的  ID

                       #region

                       List<int> has = new List<int>();

                       for (int i = 0; i < grid3d.DatasetCollecion.Count; i++)
                       {
                           if (grid3d.DatasetCollecion[i].Key.ToString().Trim().Contains(oldKey) && grid3d.DatasetCollecion[i].Key.ToString().Trim().Contains("_Copy_"))
                           {
                               //取得拷贝的数据集的个数

                               //int index = Convert.ToInt32(FileHelper.GetSpecifyString(grid3d.DatasetCollecion[i].Key.ToString().Trim(), FileHelper.GetStringNumber(grid3d.DatasetCollecion[i].Key.ToString().Trim())));
                               int index =  Convert.ToInt32(grid3d.DatasetCollecion[i].Key.ToString().Trim().Substring(grid3d.DatasetCollecion[i].Key.ToString().Trim().Length-1,1));
                               //int index = Convert.ToInt32(FileHelper.GetSpecifyString(grid3d.DatasetCollecion[i].Key.ToString().Trim(), grid3d.DatasetCollecion[i].Key.ToString().Trim().Length - 1));
                               has.Add(index);

                           }
                       }

                       if (has.Count > 0)
                       {
                           int max = has.Max();
                           int min = has.Min();

                           if (has.Count == 1)
                           {
                               //只有一个拷贝数据集
                               #region
                               if (max == 5)
                               {
                                   key = oldKey + "_Copy_" + 1.ToString();
                               }
                               else
                               {
                                   key = oldKey + "_Copy_" + (max + 1).ToString();
                               }

                               #endregion
                           }
                           if (has.Count == 2)
                           {
                               //已经有两个拷贝的数据集的状况
                               #region
                               if (max == 5)
                               {
                                   if (min == 1)
                                   {
                                       key = oldKey + "_Copy_" + 2.ToString();
                                   }
                                   else
                                   {
                                       key = oldKey + "_Copy_" + 1.ToString();
                                   }

                               }
                               else
                               {
                                   key = oldKey + "_Copy_" + (max + 1).ToString();

                               }
                               #endregion
                           }
                           if (has.Count == 3)
                           {
                               //已经有3个拷贝数据集
                               #region
                               if (max == 5)
                               {
                                   if (min == 1)
                                   {
                                       if (has.Contains(2))
                                       {
                                           key = oldKey + "_Copy_" + 3.ToString();
                                       }
                                       else
                                       {
                                           key = oldKey + "_Copy_" + 2.ToString();

                                       }

                                   }
                                   else
                                   {
                                       key = oldKey + "_Copy_" + 1.ToString();
                                   }

                               }
                               else
                               {
                                   key = oldKey + "_Copy_" + (max + 1).ToString();

                               }
                               #endregion

                           }
                           if (has.Count == 4)
                           {
                               //已经有4个拷贝数据集
                               #region
                               if (max == 5)
                               {
                                   if (min == 1)
                                   {
                                       if (has.Contains(2))
                                       {
                                           if (has.Contains(3))
                                           {
                                               key = oldKey + "_Copy_" + 4.ToString();
                                           }
                                           else
                                           {
                                               key = oldKey + "_Copy_" + 3.ToString();
                                           }

                                       }
                                       else
                                       {
                                           key = oldKey + "_Copy_" + 2.ToString();

                                       }

                                   }
                                   else
                                   {
                                       key = oldKey + "_Copy_" + 1.ToString();
                                   }

                               }
                               else
                               {
                                   key = oldKey + "_Copy_" + (max + 1).ToString();

                               }
                            #endregion
                           }

                       }
                       else
                       {
                           key = oldKey + "_Copy_" + contout.ToString();
                       }

                       #endregion


                   }
                   else if (contout>=6)
                   {
                       System.Windows.MessageBox.Show("拷贝方案已经达到5个，请删除某个方案之后再进行拷贝操作！", "提示", MessageBoxButton.OK);

                       //key = oldKey + "_Copy_" + 1.ToString();

                       return;

                   }

                   #endregion

               }
               else
               {
                   return;
               }

               //取得用户输入的项目名称

               string strnewName = key;

               HA.ModFlow.Controls.Windows.CopyResultSetName.winCopyResultSetName win = new Controls.Windows.CopyResultSetName.winCopyResultSetName(strnewName);
               win.Owner = mainWindow;
               if (win.ShowDialog().Value)
               {
                   strnewName = win.newName;
               }
               else
               {
                   //取消
                   return;
               }
               


               if (dsGrid3dCollection.Key.ToString().Trim() == "ModflowResult")
               {
                   #region

                   //DSGrid3dCollecion newDSCollection = new DSGrid3dCollecion(key);//可恶的Key是只读的  不能赋值

                   //DSModflow newDSGrid3dCollection = (DSModflow)newDSCollection;  

                   DSModflow newDSGrid3dCollection = new DSModflow(key);//我给它添加了一个构造函数    嘻嘻  这只有我和上帝知道
                   newDSGrid3dCollection.Name = strnewName;

                   foreach (DSGrid3d item in dsGrid3dCollection.Collecion)
                   {
                       List<CellCenterDataSet3d> dataset = new List<CellCenterDataSet3d>();

                       foreach (CellCenterDataSet3d cellData in item.LstValue)
                       {
                           dataset.Add(cellData);
                       }


                       DSGrid3d newGrid3d = new DSGrid3d(item.Id, dataset);
                       newGrid3d.Name = item.Name;


                       newDSGrid3dCollection.Add(newGrid3d);


                   }

                   List<BudData> budData = new List<BudData>();

                   foreach (BudData item in ((DSModflow)dsGrid3dCollection).CcfData)
                   {
                       budData.Add(item);
                   }

                   newDSGrid3dCollection.CcfData = budData;

                   //向量数据
                   if (((DSModflow)dsGrid3dCollection).VectorGridData != null)
                   {
                       newDSGrid3dCollection.VectorGridData = new DSVectorGrid3d();
                       newDSGrid3dCollection.VectorGridData.Name = ((DSModflow)dsGrid3dCollection).VectorGridData.Name;

                       

                       List<CellCenterVector3dDS> datas = new List<CellCenterVector3dDS>();
                       foreach (CellCenterVector3dDS item in ((DSModflow)dsGrid3dCollection).VectorGridData.Collecion)
                       {
                           datas.Add(item);
                       }

                       newDSGrid3dCollection.VectorGridData.ResetData(datas);
                   }

                   //逝去时间
                   if (((DSModflow)dsGrid3dCollection).MfTimeStepLabel != null)
                   {
                       List<MFTimeStepLabel> newMFTime = new List<MFTimeStepLabel>();
                       foreach (MFTimeStepLabel item in ((DSModflow)dsGrid3dCollection).MfTimeStepLabel)
                       {
                           newMFTime.Add(item);
                       }
                       newDSGrid3dCollection.MfTimeStepLabel = newMFTime;
                   }
                  //各个应力期的IBound
                   if (((DSModflow)dsGrid3dCollection).TimeStepIBound !=null )
                   {
                       List<List<int[,]>> newTimeStepIBound = new List<List<int[,]>>();
                       foreach (List <int[,]> item in ((DSModflow)dsGrid3dCollection).TimeStepIBound )
                       {
                           List<int[,]> tempTSIBound = new List<int[,]>();
                           foreach (int[,] item2 in item)
                           {
                               tempTSIBound.Add(item2);
                           }
                           newTimeStepIBound.Add(tempTSIBound);
                       }

                       newDSGrid3dCollection.TimeStepIBound = newTimeStepIBound;

                   }





                   ProjectService.DefaultService.Project.Grid3dData.MainGrid.Add(newDSGrid3dCollection);



                   UIModule.DefaultModule.ProjectViewModel.SetFirstDSSelected(newDSGrid3dCollection);

                   #endregion

               }

               if (dsGrid3dCollection.Key.ToString().Trim() == "MT3DMSResult")
               {

                   #region

                   DSGrid3dCollecion newDSGrid3dCollection = new DSGrid3dCollecion(key);
                   newDSGrid3dCollection.Name = strnewName;

                   foreach (DSGrid3d item in dsGrid3dCollection.Collecion)
                   {
                       List<CellCenterDataSet3d> dataset = new List<CellCenterDataSet3d>();

                       foreach (CellCenterDataSet3d cellData in item.LstValue)
                       {
                           dataset.Add(cellData);
                       }


                       DSGrid3d newGrid3d = new DSGrid3d(item.Id, dataset);

                       newDSGrid3dCollection.Add(newGrid3d);

                   }


                   ProjectService.DefaultService.Project.Grid3dData.MainGrid.Add(newDSGrid3dCollection);



                   UIModule.DefaultModule.ProjectViewModel.SetFirstDSSelected(newDSGrid3dCollection);

                   #endregion

               }


           }
           catch
           {
               System.Windows.MessageBox.Show("拷贝数据过程出错！");
               return;
           }



       }

       static void cbDeleteDSGrid3dCollection_CanExecute(object sender, CanExecuteRoutedEventArgs e)
       { 
           //先简单的设置为true

           e.CanExecute = true;
       }
       static void cbDeleteDSGrid3dCollection_Execute(object sender, ExecutedRoutedEventArgs e)
       {
           DSGrid3dCollecion dsGrid3dCollection = (DSGrid3dCollecion)e.Parameter;

           try
           {
               //如果当前显示数据为要删除的  则更新主程序数据为null
               if (dsGrid3dCollection!=null )
               {
                   if (dsGrid3dCollection.Key.ToString().Trim().Contains("ModflowResult"))
                   {

                       //bool isHasDSGrid3d = false;

                       foreach (DSGrid3d item in dsGrid3dCollection.Collecion)
                       {
                           if (item == ProjectService.DefaultService.Project.CurrentDSGrid)
                           {
                               //当前显示的DSGrid3d   和  CellCenter  为要删除的数据集中的数据  


                               ProjectService.DefaultService.Project.CurrentDSGrid = null;

                               ProjectService.DefaultService.Project.CurrentDSData = null;

                               //ProjectSerivce.DefaultService.Project.CurentFlowVectorData = null;



                               break;
                           }


                       }


                       //查看当前显示的向量数据是否是要删除的DSGrid3dCollection 中的数据
                       //（由于在不同 DSGrid3dCollection 之间切换的时候，不会动态的改变 DSGrid3d  和 Vector 数据  所以需要单独处理一下）
                       if (((DSModflow)dsGrid3dCollection).VectorGridData != null)
                       {
                           foreach (CellCenterVector3dDS item in ((DSModflow)dsGrid3dCollection).VectorGridData.Collecion)
                           {
                               if (item == ProjectService.DefaultService.Project.CurentFlowVectorData)
                               {
                                   //当前显示的向量数据为要删除的数据集中的数据

                                   ProjectService.DefaultService.Project.CurentFlowVectorData = null;


                                   break;

                               }

                           }

                       }
                       
                   }
                   else
                   {
                       //MT3DMSResult  和 Other  中的数据
                       
                       //if (dsGrid3dCollection.Key.ToString().Trim().Contains("MT3DMSResult"))
                       {
                           foreach (DSGrid3d item in dsGrid3dCollection.Collecion)
                           {
                               if (item == ProjectService.DefaultService.Project.CurrentDSGrid)
                               {
                                   //当前显示的DSGrid3d  vector 和CellCenter为要删除的数据集中的数据

                                   ProjectService.DefaultService.Project.CurrentDSGrid = null;

                                   ProjectService.DefaultService.Project.CurrentDSData = null;

                                   //ProjectSerivce.DefaultService.Project.CurentFlowVectorData = null;

                                   break;
                               }
                               
                           }
                       }

                   }



               }

               //删除数据集并更新控件树形目录视图
               ProjectService.DefaultService.Project.Grid3dData.MainGrid.Remove(dsGrid3dCollection);
           }
           catch
           {
               System.Windows.MessageBox.Show("删除对应的数据集过程出错！");

               return;
           }





       }

       static void cbDeleteDSGrid3d_CanExecute(object sender, CanExecuteRoutedEventArgs e)
       { 
           //先简单的设置为true

           e.CanExecute = true;

       }
       static void cbDeleteSGrid3d_Execute(object sender, ExecutedRoutedEventArgs e)
       {

           DSGrid3d dsGrid3d = (DSGrid3d)e.Parameter;

           try
           {

               if (ProjectService.DefaultService.Project != null && ProjectService.DefaultService.Project.Grid3dData != null && ProjectService.DefaultService.Project.Grid3dData.MainGrid != null)
               {

                   Grid3d grid3d = ProjectService.DefaultService.Project.Grid3dData.MainGrid;

                   if (grid3d.DatasetCollecion != null)
                   {
                       for (int i = 0; i < grid3d.DatasetCollecion.Count; i++)
                       {
                           if (grid3d.DatasetCollecion[i].Key.ToString().Trim() == "OtherDataSetResult")
                           {

                               //如果当前显示数据为要删除的  则更新主程序数据为null

                               ProjectService.DefaultService.Project.CurrentDSData = null; 


                               //删除数据集并更新控件树形目录视图

                               grid3d.DatasetCollecion[i].RemoveDSGrid3d(dsGrid3d);

                               break;
                           }

                       }

                   }


               }

           }
           catch
           {
               System.Windows.MessageBox.Show("对不起，删除数据过程出错！");

               return;

           }




       }













       static void cbViewVector_Executed(object sender, ExecutedRoutedEventArgs e)
       {
           HA.ModFlow.Controls.Windows.Grids.winVectorView win = new Controls.Windows.Grids.winVectorView(ProjectService.DefaultService.Project.CurentFlowVectorData, "未知的名称");
           win.Owner = mainWindow;
           win.ResizeMode = ResizeMode.NoResize;
           win.WindowStartupLocation = WindowStartupLocation.CenterScreen;
           win.ShowDialog();
       }

       static void cbViewVector_CanExecute(object sender, CanExecuteRoutedEventArgs e)
       {
           e.CanExecute = true;
       }

       static void cbEditScatterPoint_CanExecute(object sender, CanExecuteRoutedEventArgs e)
       {
           Scatter2D sca = e.Parameter as Scatter2D;
           List<ScatterPoint> scatter = sca.DataSet;
           if (sca != null)
           {
               if (scatter != null)
               {
                   e.CanExecute = true;
               }
           }
       }

       static void cbEditScatterPoint_Executed(object sender, ExecutedRoutedEventArgs e)
       {
           Scatter2D sca =(Scatter2D) (e.Parameter as Scatter2D).Clone ();
           List<ScatterPoint> scatter = sca.DataSet;
           if (scatter != null)
           {
               HA.ModFlow.Controls.Windows.Scatter.winScatter2DPoints win = new Controls.Windows.Scatter.winScatter2DPoints(scatter, sca.Name );
               win.Owner = mainWindow;
               win.ResizeMode = ResizeMode.NoResize;
               win.WindowStartupLocation = WindowStartupLocation.CenterScreen;
               if (win.ShowDialog().Value)
               {
                   ProjectService.DefaultService.Project.Scatter2dData.Replace(sca.Key.ToString(), sca);
           
               }
           }
       }

       static void cbGenerateVector_Executed(object sender, ExecutedRoutedEventArgs e)
       {


               //好麻烦 有一个问题是由于dos运行完毕后，缺乏运行正确和计算正确性验算机制，可能存在计算出问题的情况
                //计算出问题的时候，各应力期IBound和各应力期IHead等数据个数不一致，此时为避免一些意外的处理，使用主程序的IBound
          
               DSModflow modflow = e.Parameter as DSModflow;

               if (modflow == null)
               {
                   return;
               }

               bool isUseStressStepIBound = true;

                List<List<int[,]>> stressStpIBound = new List<List<int[,]>>();

                #region  判断读取IBound的数据和IHead的数据等是否一致 如果一致则使用读取IBound，如果不一致则使用主程序的IBound

                if (ProjectService.DefaultService.Project != null)
                {

                    if (modflow.TimeStepIBound != null && modflow.MfTimeStepLabel != null)
                    {
                        if (modflow.TimeStepIBound.Count != modflow.MfTimeStepLabel.Count)
                        {
                            //从文件中读取的IBound数据和IHead数据的各应力期的数据个数不一致 原因可能是项目计算出错

                            isUseStressStepIBound = false;
                        }
                        else
                        {
                            if (modflow.TimeStepIBound.Count > 0)
                            {
                            }
                            else
                            {
                                isUseStressStepIBound = false;
                            }

                        }

                    }
                    else
                    {
                        isUseStressStepIBound = false;

                    }

                }
                else
                {
                    isUseStressStepIBound = false;

                }

                #endregion



                if (isUseStressStepIBound)
                {
                    //使用读取的各应力期的IBound

                    modflow.GenerateVectors( ProjectService.DefaultService.Project.Grid3dData.MainGrid.ModFlowGrid.RotationZ);

                }
                else
                {
                    if (modflow.TimeStepIBound ==null )
                    {
                        modflow.TimeStepIBound = new List<List<int[,]>>();
                    }

                    modflow.TimeStepIBound.Clear();

                    List<int[,]> temp=new List<int[,]> ();

                    List<int[,]> mainIBound=ProjectService.DefaultService.Project.Grid3dData.MainGrid.ModFlowGrid.WaterGrid.GetIBounds();
                   
                    foreach ( int[,] layerIBound in mainIBound)
                    {
                        temp.Add((int[,])layerIBound.Clone());
                    }

                    modflow.TimeStepIBound.Add(temp);


                    modflow.GenerateVectors(ProjectService.DefaultService.Project.Grid3dData.MainGrid.ModFlowGrid.RotationZ);

                
                }



                //DSModflow modflow = e.Parameter as DSModflow;

                //modflow.GenerateVectors(ProjectSerivce.DefaultService.Project.Grid3dData.MainGrid.ModFlowGrid.WaterGrid.GetIBounds(),
                //    ProjectSerivce.DefaultService.Project.Grid3dData.MainGrid.ModFlowGrid.RotationZ

                //    );



        



       }

       static void cbGenerateVector_CanExecute(object sender, CanExecuteRoutedEventArgs e)
       {
           e.CanExecute = !ProjectService.DefaultService.BNullProj;
       }

       static void cbViewDSValue_Executed(object sender, ExecutedRoutedEventArgs e)
       {
           DSGrid3d ds = e.Parameter as DSGrid3d;

           int index = 0;

           PCStep step = UIModule.DefaultModule.ProjectViewModel.TsvViewModel.SelectedStep;

           if (step != null)
           {
               index = step.Index;

           }



           if (ds != null)
           {
               HA.ModFlow.Infrastructure.CellCenterDataSet3d data = ds.GetDataSet(index);
               if (data != null)
               {

                   List<int[,]> arry = data.EffIBound;
                   List<int[,]> ibound = new List<int[,]>();
                   ibound.AddRange(arry);

                   HA.ModFlow.Controls.Windows.Grids.winDSViewValue win = new Controls.Windows.Grids.winDSViewValue(data.Datas, (index + 1).ToString() + " " + data.Label, ibound);
                   win.Title = ds.Name;
                   win.Owner = mainWindow;
                   win.ResizeMode = ResizeMode.NoResize;
                   win.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                   win.ShowDialog();
               }
           }
       }

       static void cbViewDSValue_CanExecute(object sender, CanExecuteRoutedEventArgs e)
       {
           DSGrid3d ds = e.Parameter as DSGrid3d;
           if (ds != null)
           {
               e.CanExecute = true;
           }
       }

       /// <summary>
       /// 
       /// </summary>
       /// <param name="sender"></param>
       /// <param name="e"></param>
       static void cbFlowBudget_Executed(object sender, ExecutedRoutedEventArgs e)
       {
           HA.Data.DSModflow ds = e.Parameter as HA.Data.DSModflow;

           if (ds == null)
           {
               return;
           }
           if (ds.CcfData.Count <= 0)
           {
               return;
           }

           if (ds.MfTimeStepLabel .Count <=0)
           {
               return;
           }

           //得到选择的单元格数
           List<int> number = HA.ModFlow.Application.GisModule.DefaultModule.GetGridSelectedCellIndexes();
           List<int[]> cell = new List<int[]>();
           for (int i = 0; i < number.Count; i++)
           {
               cell.Add(ProjectService.DefaultService.Project.MfData.GridData.GetIJK(number[i]));
           }

           
           HA.ModFlow.Controls.Windows.Grids.winFlowBudget win = new Controls.Windows.Grids.winFlowBudget(ds, ds.MfTimeStepLabel.Count - 1, cell);
           //HA.ModFlow.Controls.Windows.Grids.winFlowBudget win = new Controls.Windows.Grids.winFlowBudget(ds, ProjectSerivce.DefaultService.Project.MfData.MfResult.MfTimeStepLabel.Count - 1, cell);
           win.Owner = mainWindow;
           win.ResizeMode = ResizeMode.NoResize;
           win.WindowStartupLocation = WindowStartupLocation.CenterScreen;
           win.ShowDialog();

       }


       static void cbFlowBudget_CanExecute(object sender, CanExecuteRoutedEventArgs e)
       {
           e.CanExecute = !ProjectService.DefaultService.BNullProj;
       }

       static void cbCCFToDS_Executed(object sender, ExecutedRoutedEventArgs e)
       {
           DSModflow modflow = e.Parameter as DSModflow;

           modflow.CCFToDataSet();
           //modflow.CCFToDataSet(ProjectSerivce .DefaultService .Project .MfData .MfResult .MfTimeStepLabel );


       }

       static void cbCCFToDS_CanExecute(object sender, CanExecuteRoutedEventArgs e)
       {
           e.CanExecute = !ProjectService.DefaultService.BNullProj;
       }

       static void cbGrid3dProp_Executed(object sender, ExecutedRoutedEventArgs e)
       {
           Grid3d grid = e.Parameter as Grid3d;
           grid = ProjectService.DefaultService.Project.Grid3dData.MainGrid;
           HA.ModFlow.Controls.Windows.Grids.winGridProperties win = new Controls.Windows.Grids.winGridProperties(grid);
           win.Owner = mainWindow;
           win.ResizeMode = ResizeMode.NoResize;
           win.WindowStartupLocation = WindowStartupLocation.CenterScreen;
           win.ShowDialog();




       }

       static void cbGrid3dProp_CanExecute(object sender, CanExecuteRoutedEventArgs e)
       {

           e.CanExecute = !ProjectService.DefaultService.BNullProj;
           
       }

       static void cbScatterToModflowLayer_Executed(object sender, ExecutedRoutedEventArgs e)
       {

           Scatter2D scatter = (Scatter2D)e.Parameter;

           DataOperationModule.DefaultModule.Scatter2DToModlfowLayer(scatter,ProjectService.DefaultService.Project);

        
           
         
       }

       static void cbScatterToModflowLayer_CanExecute(object sender, CanExecuteRoutedEventArgs e)
       {

           if (!ProjectService.DefaultService.BNullProj)
           {
               if (ProjectService.DefaultService.Project.MfData != null)
               {
                   e.CanExecute = true;
               }
               
           }
          
       }


       static void cbScatter2dToGrid3d_CanExecuted(object sender,CanExecuteRoutedEventArgs e)
       {
           if (!ProjectService .DefaultService .BNullProj )
           {
                Scatter2D sca = e.Parameter as Scatter2D;
                List<ScatterPoint> scatter = sca.DataSet;

               if (sca != null && scatter != null)
               {
                   if (scatter.Count > 0 && ProjectService .DefaultService .Project .Grid3dData .Grids .Count >0)
                   {
                       e.CanExecute = true;
                   }
               }
           }       
       }

       static void cbScatter2dToGrid3d_Executed(object sender, ExecutedRoutedEventArgs e)
       {

           //伪代码

           //return;//暂时不让进入

           # region 刘加测试克里金

           //Scatter2D pts = e.Parameter as Scatter2D;

           ////计算实验变差值
          
           //List <Point2D> Points = new List<Point2D>();
           //List <double>  Values = new List<double>();
           //foreach (ScatterPoint pt in pts.DataSet)
           //{
           //    Points.Add(new Point2D(pt.X, pt.Y));
           //    Values.Add(pt.Values[0]);
           //}

           //OridinateKriging krig = new OridinateKriging(Points, Values);

           //Point2D[,] resultPts = new Point2D[201, 201];

           //for (int i = 0; i < 201; i++)
           //{
           //    for (int j = 0; j < 201; j++)
           //    {
           //        resultPts[i, j] = new Point2D(-500 + 5 * j, -500 + 5 * i);
           //    }
           //}

           //List<double> resultValues = new List<double>();

           //foreach (Point2D pt in resultPts)
           //{
           //    resultValues.Add(krig.GetValue(pt)); 
           //}


           //int n = 1;   
       
           //return;





           # endregion



           try
           {                         
               #region

               Scatter2D sca = e.Parameter as Scatter2D;
               //List<ScatterPoint> scatter = sca.DataSet;

               double[, ,] valueResult = null;

               List<int[,]> iBound = null;

               if (!ProjectService.DefaultService.BNullProj && ProjectService.DefaultService.Project != null && ProjectService.DefaultService.Project.Grid3dData != null && ProjectService.DefaultService.Project.Grid3dData.MainGrid != null && ProjectService.DefaultService.Project.Grid3dData.MainGrid.ModFlowGrid != null)
               {
                   if (ProjectService.DefaultService.Project.Grid3dData.MainGrid.ModFlowGrid.WaterGrid != null)
                   {
                       iBound = (List<int[,]>)ProjectService.DefaultService.Project.Grid3dData.MainGrid.ModFlowGrid.WaterGrid.GetIBounds();
                   }
               }

               double invalidValue = -999.0;//无效值 应该从  二维离散点的数据集中取得信息  暂时使用默认值

               string valueNameLabel = "";//用于CellCenterDataSet3d中构造标签


               //网格某一层的顶部或者底部的平面网格中心点的value信息  网格单元为平面的平行四边形
               double[,] xyValueResult = DataOperationModule.DefaultModule.Scatter2DToGrid3d(sca, ProjectService.DefaultService.Project,ref valueNameLabel );


               int nRow = ProjectService.DefaultService.Project.Grid3dData .MainGrid .ModFlowGrid .RowsCount;
               int nCol = ProjectService.DefaultService.Project.Grid3dData.MainGrid.ModFlowGrid.ColsCount;
               int nLayer = ProjectService.DefaultService.Project.Grid3dData.MainGrid.ModFlowGrid.LayersCount;

               CellCenterDataSet3d cellCenterDS3D=null ;

               if (xyValueResult != null && xyValueResult.GetLength(0) > 0 && xyValueResult.GetLength(1) > 0 && iBound != null && iBound.Count > 0)
               {
                   if (nLayer == iBound.Count && xyValueResult.GetLength(0) == iBound[0].GetLength(0) && xyValueResult.GetLength(1) == iBound[0].GetLength(1))
                   {
                       //三维单元格 体单元格中心点的value值
                       valueResult = new double[nRow, nCol, nLayer];

                       for (int row = 0; row < xyValueResult.GetLength(0); row++)
                       {
                           for (int col = 0; col < xyValueResult.GetLength(1); col++)
                           {
                               for (int layer = 0; layer < nLayer; layer++)
                               {
                                   valueResult[row, col, layer] = xyValueResult[row, col];
                               }
                           }
                       }

                       //保存计算结果
                        cellCenterDS3D = new CellCenterDataSet3d(valueResult, iBound, invalidValue);

                        cellCenterDS3D.Label = sca.Key.ToString () + valueNameLabel;
                 

                   }
               }

               #endregion

               #region

               if (cellCenterDS3D != null)
               {

                   string keyDSGrid3d = "OtherDataSetResult";

                   string dsLabel = sca.Key.ToString() + "二维离散点";

                   string cellDataLabel = "scatter2d " + sca.Key.ToString() + " " + valueNameLabel;//DSGrid3d的标记

                   bool isHas = false;

                   DSGrid3dCollecion dsGrid3dCollection = null;
                   DSGrid3d dsGrid3d = null;

                   if (ProjectService.DefaultService.Project.Grid3dData.MainGrid.DatasetCollecion.Count > 0)
                   {
                       for (int i = 0; i < ProjectService.DefaultService.Project.Grid3dData.MainGrid.DatasetCollecion.Count; i++)
                       {
                           dsGrid3dCollection = ProjectService.DefaultService.Project.Grid3dData.MainGrid.DatasetCollecion[i];

                           if (dsGrid3dCollection.Key.ToString().Trim() == keyDSGrid3d.Trim())
                           {
                               isHas = true;

                               bool isContainsDS = false;

                               for (int j = 0; j < dsGrid3dCollection.Collecion.Count; j++)
                               {

                                   dsGrid3d = dsGrid3dCollection.Collecion[j];

                                   if (dsGrid3d.Id.Trim() == cellDataLabel.Trim())
                                       //if (dsGrid3d.Id.Trim() == dsLabel.Trim())
                                   {
                                       isContainsDS = true;



                                       //需求修改  旧的需求：每个二维离散点文件对应一个 DSGird3d，每个DSGrid3d包含多个CellCenterDataSet3d
                                       //新的需求：每个二维离散点文件中的Value 各对应一个DSGrid3d，每个DSGrid3d对应一个CellCemterDataSet3d

                                       //


                                       //已经存在对应的DSGrid3d

                                       List<CellCenterDataSet3d> cellCenterDS = new List<CellCenterDataSet3d>();
                                       cellCenterDS.Add(cellCenterDS3D);

                                       //dsGrid3d = new DSGrid3d(dsLabel, cellCenterDS);
                                       //dsGrid3d = new DSGrid3d(cellDataLabel, cellCenterDS);

                                       dsGrid3dCollection.Collecion[j] = new DSGrid3d(cellDataLabel, cellCenterDS);


                                       break;


                                       //bool IsContainsCellDS = false;
                                       //for (int k = 0; k < dsGrid3d.LstValue.Count; k++)
                                       //{
                                       //    if (dsGrid3d.LstValue[k].Label.Trim() == cellDataLabel.Trim())
                                       //    {
                                       //        IsContainsCellDS = true;

                                       //        dsGrid3d.LstValue[k] = cellCenterDS3D;

                                       //        break;
                                       //    }

                                       //}
                                       //if (IsContainsCellDS == false)
                                       //{
                                       //    //需要添加CellCenterDataSet

                                       //    dsGrid3d.LstValue.Add(cellCenterDS3D);

                                       //    break;

                                       //}




                                   }
                                   if (isContainsDS==true )
                                   {
                                       break;
                                   }
                               }
                               if (isContainsDS == false)
                               {
                                   //需要添加 DSGrid3d
                                   List<CellCenterDataSet3d> cellCenterDS = new List<CellCenterDataSet3d>();
                                   cellCenterDS.Add(cellCenterDS3D);

                                   dsGrid3d = new DSGrid3d(cellDataLabel, cellCenterDS);
                                   //dsGrid3d = new DSGrid3d(dsLabel, cellCenterDS);


                                   dsGrid3dCollection.Collecion.Add(dsGrid3d);

                                   break;

                               }
                               if (isContainsDS==true )
                               {
                                   break;
                               }

                           }
                       }
                       if (isHas == false)
                       {
                           //需要添加  DSGrid3dCollecion

                           dsGrid3dCollection = new DSGrid3dCollecion(keyDSGrid3d);

                           List<CellCenterDataSet3d> cellCenterDS = new List<CellCenterDataSet3d>();
                           cellCenterDS.Add(cellCenterDS3D);

                           dsGrid3d = new DSGrid3d(cellDataLabel, cellCenterDS);
                           //dsGrid3d = new DSGrid3d(dsLabel, cellCenterDS);


                           dsGrid3dCollection.Collecion.Add(dsGrid3d);

                       }

                   }
                   else 
                   {
                       //需要添加   DSGrid3dCollecion

                       dsGrid3dCollection = new DSGrid3dCollecion(keyDSGrid3d);

                       List<CellCenterDataSet3d> cellCenterDS = new List<CellCenterDataSet3d>();
                       cellCenterDS.Add(cellCenterDS3D);

                       dsGrid3d = new DSGrid3d(cellDataLabel, cellCenterDS);
                       //dsGrid3d = new DSGrid3d(dsLabel, cellCenterDS);

                       dsGrid3dCollection.Collecion.Add(dsGrid3d);
                   
                   }

                   ProjectService.DefaultService.Project.Grid3dData.MainGrid.Add(dsGrid3dCollection);


                   ///重置当前项目中的显示条件
                   ///


                   UIModule.DefaultModule.ProjectViewModel.SetFirstDSSelected(dsGrid3dCollection);

               }

               #endregion

           }
           catch (Exception ex)
           {
               //MessageBox.Show("二维离散点差值到网格过程出错！");
               MessageBox.Show(ex.Message);
               return;
           }


       }


       /// <summary>
       /// 命令的具体执行方法   离散点边框转换网格
       /// </summary>
       static void cbScatterBoundToGrid3D_Execute(object sender, ExecutedRoutedEventArgs e)
       {
           try
           {



               #region 提示信息:如果有旧的网格  先删除就网格
               if (ProjectService.DefaultService.Project.Grid3dData.Grids.Count > 0)
               {
                   if (MessageBox.Show("创建新的三维网格将会使旧的网格被删除，是否继续？", "提示", MessageBoxButton.OKCancel, MessageBoxImage.Information) == MessageBoxResult.Cancel)
                   {
                       return;
                   }
                   else
                   {
                       if (ProjectService.DefaultService.Project.MfData != null)
                       {
                           if (MessageBox.Show("创建新的三维网格将会使当前MODFLOW与MODPATH数据删除，是否删除", "提示", MessageBoxButton.OKCancel, MessageBoxImage.Information) == MessageBoxResult.Cancel)
                           {
                               return;
                           }
                       }
                   }
               }
               #endregion

               Scatter2D sca = e.Parameter as Scatter2D;
               List<ScatterPoint> scatter = sca.DataSet;


               ///在这里循环所有可用的Coverage,然后弹出窗体以提供用户选择

               int[] indexInList = new int[1];  //存储使用哪个value值  顺序为List<string> _valueNames中的index
               //List<double> valueScatter2D = new List<double>();

               winConceptualFrame win = new winConceptualFrame(sca, ChooseConfigeType.Scatter2DValueChoose, indexInList);
               win.Owner = mainWindow;
               win.ResizeMode = ResizeMode.NoResize;
               win.WindowStartupLocation = WindowStartupLocation.CenterScreen;
               if (win.ShowDialog() == true)
               {
                   if (win.DialogResult == true)
                   {
                       if (indexInList != null && indexInList[0] >= 0 && indexInList[0] <= scatter.Count - 1)
                       {


                           #region 根据离散点数据信息  计算新的网格的坐标信息

                           double orgX = 0;//起始点坐标信息
                           double orgY = 0;
                           double orgZ = 0;

                           double xLen = 10;//网格长度信息
                           double yLen = 10;
                           double zLen = 2;

                           int xCellNum = 12;//单元格数目
                           int yCellNum = 12;
                           int zCellNum = 1;

                           double rotate = 0;//旋转

                           //X Y Z轴各个方向均扩展10%
                           //Z轴方向单元格个数一直为1.
                           //XY方向上Cell的个数<=12,>=24;由限制条件：最外围点的靠边框一侧（扩展的10%长度部分）最多有2个单元格，最少有1个单元格而计算取得。
                           //简化处理方案：  XY方向单元格的个数定为12(扩展一个) ； Z方向1个 ； rotate=0；len某方向上只有一个离散点或者最远两个点的距离<=10则只有一个单元格

                           #region
                           if (scatter != null)
                           {
                               List<double> xCoor = new List<double>();//存储二维离散点信息中X方向的信息  其Count等于二维离散点的个数
                               List<double> yCoor = new List<double>();
                               List<double> valueScatter2d = new List<double>();

                               //存储各个离散点（string）的value（List）值信息
                               //Dictionary<string, List<double>> valueDic = new Dictionary<string, List<double>>();

                               #region 二维离散点在各个方向的信息
                               for (int i = 0; i < scatter.Count; i++)
                               {
                                   xCoor.Add(scatter[i].X);
                                   yCoor.Add(scatter[i].Y);

                                   if (scatter[i].Values != null && scatter[i].Values.Count > 0)
                                   {
                                       //string key = i.ToString();
                                       //List<double> value = new List<double>();

                                       //for (int j = 0; j < scatter[i].Values.Count; j++)
                                       //{
                                       //    key = scatter[i].Id;
                                       //    value.Add(scatter[i].Values[j]);
                                       //}

                                       //valueDic.Add(key, value);

                                       valueScatter2d.Add(scatter[i].Values[indexInList[0]]);
                                   }
                                   else
                                   {
                                       //string key = i.ToString();
                                       //List<double> value = new List<double>();
                                       //value.Add(0);

                                       //valueDic.Add(key, value);

                                       valueScatter2d.Add(0);
                                   }
                               }
                               #endregion

                               MinMaxDiffResult x = GetMinMaxDifference.GetValueStatistics(xCoor);//X方向相距最远的两个点的信息
                               MinMaxDiffResult y = GetMinMaxDifference.GetValueStatistics(yCoor);//X方向相距最远的两个点的信息

                               //MinMaxDiffResult zValue = null;//Value信息
                               MinMaxDiffResult zValue = GetMinMaxDifference.GetValueStatistics(valueScatter2d);//Value信息

                               #region  计算zValue  按时按照value中的差值较大者计算  例如：有Top，Bot1两种，则取两者中差值较大的一种使用
                               //int numValue = 0;

                               //foreach (var item in valueDic)
                               //{
                               //    numValue = item.Value.Count;//取得每个离散点有多少个value值
                               //    break;
                               //}
                               //if (numValue > 0)
                               //{
                               //    for (int i = 0; i < numValue; i++)//遍历取值：例如Top，Bot1，Bot2，Bot3
                               //    {
                               //        List<double> temp = new List<double>();//例如存储所有离散点的 Top 的value值
                               //        foreach (var item in valueDic)
                               //        {
                               //            temp.Add(item.Value[i]);//依次取得各个离散点的 Top的value值
                               //        }
                               //        if (zValue == null)
                               //        {
                               //            zValue = GetMinMaxDifference.GetValueStatistics(temp);//计算其中最大最小值及差值
                               //        }
                               //        else
                               //        {
                               //            MinMaxDiffResult tempResult = GetMinMaxDifference.GetValueStatistics(temp);
                               //            if (tempResult != null)
                               //            {
                               //                if (zValue.Dirrerence < tempResult.Dirrerence)
                               //                {
                               //                    zValue = tempResult;
                               //                }
                               //            }
                               //        }
                               //    }
                               //}
                               #endregion

                               if (x != null && y != null && zValue != null)
                               {

                                   #region Len
                                   if (x.Dirrerence != 0.0)//等于0时，总长度为10
                                   {
                                       //如果不是一个离散点并且X方向最远的两个离散点的距离不等于0  
                                       //区别多个离散点X坐标相同 在Y方向一条直线的（X方向单元格个数设置为1）情况
                                       xLen = x.Dirrerence * 1.2;
                                   }
                                   if (y.Dirrerence != 0.0)
                                   {
                                       yLen = y.Dirrerence * 1.2;
                                   }
                                   if (zValue.Dirrerence != 0.0)
                                   {
                                       zLen = zValue.Dirrerence * 1.2;
                                   }

                                   #endregion

                                   #region CellNum
                                   if (xCoor.Count <= 1 || xLen <= 10)//否则默认使用12个单元格
                                   {
                                       //只有一个二维离散点或者多个离散点之间的距离太近  则设置一个单元格
                                       xCellNum = 1;
                                   }

                                   if (yCoor.Count <= 1 || yLen <= 10)
                                   {
                                       yCellNum = 1;
                                   }
                                   #endregion

                                   #region org

                                   if (xCellNum != 1)
                                   {
                                       //orgX = x.Min - xLen / xCellNum;//扩展一个单元格
                                       orgX = x.Min - xLen / 1.2 * 0.1;//扩展一个单元格
                                   }
                                   else
                                   {
                                       //只有一个单元格 ：一个点在单元格中间或者多个点挤在一个单元格中
                                       if (xCoor.Count <= 1)
                                       {
                                           orgX = x.Min - xLen / 1.2 * 0.5;
                                       }
                                       else
                                       {
                                           orgX = x.Min - xLen / 1.2 * 0.1;
                                       }

                                   }
                                   if (yCellNum != 1)
                                   {
                                       orgY = y.Min - yLen / 1.2 * 0.1;
                                   }
                                   else
                                   {
                                       if (yCoor.Count <= 1)
                                       {
                                           orgY = y.Min - yLen / 1.2 * 0.5;
                                       }
                                       else
                                       {
                                           orgY = y.Min - yLen / 1.2 * 0.1;
                                       }
                                   }

                                   if (zValue.Dirrerence != 0.0)
                                   {
                                       orgZ = zValue.Min - zLen / 1.2 * 0.1;
                                   }
                                   else
                                   {
                                       orgZ = zValue.Min - zLen / 1.2 * 0.5;
                                   }

                                   #endregion

                               }
                               else
                               {
                                   //例如二维离散点个数为0的时候  如果有旧网格则使用旧网格数据，否则构造初始网格

                                   orgX = 0;//起始点坐标信息
                                   orgY = 0;
                                   orgZ = 0;
                                   xLen = 100;//网格长度信息
                                   yLen = 100;
                                   zLen = 10;
                                   xCellNum = 10;//单元格数目
                                   yCellNum = 10;
                                   zCellNum = 1;
                                   rotate = 0;//旋转

                               }

                           }
                           else
                           {
                               //例如二维离散点个数为0的时候  如果有旧网格则使用旧网格数据，否则构造初始网格
                               orgX = 0;//起始点坐标信息
                               orgY = 0;
                               orgZ = 0;
                               xLen = 100;//网格长度信息
                               yLen = 100;
                               zLen = 10;
                               xCellNum = 10;//单元格数目
                               yCellNum = 10;
                               zCellNum = 1;
                               rotate = 0;//旋转
                           }
                           #endregion
                           #endregion

                           #region 配置 GridConfig  信息

                           GridConfig oldGridConfig = null;
                           GridConfig config;

                           if (ProjectService.DefaultService.Project.Grid3dData.MainGrid == null)
                           {
                           }
                           else
                           {
                               oldGridConfig = ProjectService.DefaultService.Project.Grid3dData.MainGrid.ModFlowGrid.Config;
                           }
                           if (oldGridConfig != null)
                           {
                               config = new GridConfig(false, xLen, yLen, zLen, orgX, orgY, orgZ, rotate, oldGridConfig.BiasX, oldGridConfig.BaseCellSizeX, oldGridConfig.LimitCellSizeX, xCellNum, oldGridConfig.IsUseBLX,
                                   oldGridConfig.BiasY, oldGridConfig.BaseCellSizeY, oldGridConfig.LimitCellSizeY, yCellNum, oldGridConfig.IsUseBLY,
                                   oldGridConfig.BiasZ, oldGridConfig.BaseCellSizeZ, oldGridConfig.LimitCellSizeZ, zCellNum, oldGridConfig.IsUseBLZ);
                           }
                           else
                           {
                               //这里需要加入有关的判断，考虑旧网格不存在的情况
                               config = new GridConfig(false, yCellNum, xCellNum, zCellNum, xLen, yLen, zLen, orgX, orgY, orgZ, rotate);
                           }
                           #endregion

                           #region 调用窗体 winGridConfig 用户配置参数  更新网格

                           winGridConfig wc = new winGridConfig(config);
                           wc.Owner = mainWindow;
                           wc.ResizeMode = ResizeMode.NoResize;
                           wc.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                           if (wc.ShowDialog() == true)
                           {
                               //确定是否沿用前一key值，以保证绘图系统的正确识别，这里三维网格，目前被认为是唯一的
                               Grid3d gd;
                               if (ProjectService.DefaultService.Project.Grid3dData.Grids.Count > 0)
                               {
                                   gd = new Grid3d(wc.GridData, ProjectService.DefaultService.Project.Grid3dData.MainGrid.Key.ToString());
                               }
                               else
                               {
                                   gd = new Grid3d(wc.GridData);
                               }
                               if (ProjectService.DefaultService.Project.MfData != null)
                               {
                                   ProjectService.DefaultService.Project.DeleteModflow();
                               }
                               ProjectService.DefaultService.Project.Grid3dData.MainGrid = gd;
                           }
                           #endregion
                       }
                   }
               }
           }
           catch
           {
               MessageBox.Show("二维离散点边框转换成网格过程出错！");
               return;
           }

       }

      /// <summary>
      /// 条件判断   是否允许离散点边框转换网格
      /// </summary>
      /// <param name="sender"></param>
      /// <param name="e"></param>
       static void cbScatterBoundToGrid3D_CanExecute(object sender,CanExecuteRoutedEventArgs e)
       {

           if (ProjectService.DefaultService.BNullProj==false )
           {
               Scatter2D sca = e.Parameter as Scatter2D;
               List<ScatterPoint> scatter = sca.DataSet;

               if (sca != null && scatter != null)
               {
                   if (scatter.Count > 0)
                   {
                       e.CanExecute = true;
                   }
                   else
                   {
                       e.CanExecute = false;
                   }
               }
               else
               {
                   e.CanExecute = false;
               }

           }
           else
           {
               e.CanExecute = false;
           }

        

       }








       static void cbRemoveScatter3D_Executed(object sender, ExecutedRoutedEventArgs e)
       {
           Scatter3D data = (Scatter3D)e.Parameter;
           if (data != null)
           {
               ProjectService.DefaultService.Project.Scatter3dData.Remove(data);

           }
           
       }

       static void cbRemoveScatter3D_CanExecute(object sender, CanExecuteRoutedEventArgs e)
       {
           e.CanExecute = !ProjectService.DefaultService.BNullProj;
       }

       static void cbAddScatter3D_Executed(object sender, ExecutedRoutedEventArgs e)
       {
           Scatter3D scatter = ProjectService.DefaultService.Project.Scatter3dData.CreateNew();

           ProjectService.DefaultService.Project.Scatter3dData.Add(scatter);


       }

       static void cbAddScatter3D_CanExecute(object sender, CanExecuteRoutedEventArgs e)
       {
           e.CanExecute = !ProjectService.DefaultService.BNullProj;
       }

       static void cbRemoveSatter2D_Executed(object sender, ExecutedRoutedEventArgs e)
       {
           Scatter2D data = (Scatter2D)e.Parameter;
           if (data != null)
           {
               ProjectService.DefaultService.Project.Scatter2dData.Remove(data);

           }

       }

       static void cbRemoveSatter2D_CanExecute(object sender, CanExecuteRoutedEventArgs e)
       {
           e.CanExecute = !ProjectService.DefaultService.BNullProj;
       }

       static void cbAddSactter2D_Executed(object sender, ExecutedRoutedEventArgs e)
       {

           Scatter2D scatter = ProjectService.DefaultService.Project.Scatter2dData.CreateNew();
           scatter.ValueNames.Add(scatter.Key.ToString());
           ProjectService.DefaultService.Project.Scatter2dData.Add(scatter);

       }

       static void cbAddSactter2D_CanExecute(object sender, CanExecuteRoutedEventArgs e)
       {

           e.CanExecute = !ProjectService.DefaultService.BNullProj;
       }



    }
}
